from PySide2.QtWidgets import QWidget, QHBoxLayout, QPushButton, QLabel, QLineEdit, QListWidget, QListView, QListWidgetItem
from PySide2.QtCore import Signal, Qt

class SearchView(QWidget):

    searchHistory = []
    search_signal = Signal(str)
    today_signal = Signal()

    def __init__(self):
        super(SearchView, self).__init__()
        self.setupUi()

    def setSearchHistorys(self, searchs):
        for search in searchs:
             self.setSearchHistory(search)

    def setSearchHistory(self, search):
        exist = False
        for text in self.searchHistory:
            if text == search:
                exist = True
        if exist == False:
            self.setItem(search)
            self.searchHistory.append(search)
        return exist

    def setupUi(self):
        self.layout = QHBoxLayout(self)

        self.searchEdit = QLineEdit()
        self.searchEdit.setPlaceholderText("搜索")
        self.searchEdit.returnPressed.connect(self.onReturnPressed)

        self.searchButton = QPushButton("搜索")
        self.searchButton.clicked.connect(self.onClickSearch)

        self.listWidget = QListWidget()
        # self.listWidget.setViewMode(QListView.IconMode)
        self.listWidget.setMaximumHeight(40)
        self.listWidget.setFlow(QListView.LeftToRight)
        self.listWidget.itemClicked.connect(self.onClickItem)

        self.pushButton = QPushButton("今天")
        self.pushButton.clicked.connect(self.today_signal)

        self.layout.addWidget(self.searchEdit)
        self.layout.addWidget(self.searchButton)
        self.layout.addWidget(self.listWidget)
        self.layout.addWidget(self.pushButton)

        self.layout.setStretchFactor(self.listWidget, 1)
            
    def onReturnPressed(self):
        self.__search()

    def setItem(self, text):
        if text == None or len(text) == 0:
            return
        self.item = QListWidgetItem(text)
        self.listWidget.addItem(self.item)

    def onClickItem(self, item):
        text = str(item.text())
        self.searchEdit.setText(text)
        self.__search()

    def onClickSearch(self):
        self.__search()

    def __search(self):
        text = str(self.searchEdit.text())
        self.search_signal.emit(text)
